using Domain.Entities;
using Domain.Entities.Enums;
using Domain.Mail;
using Domain.Misc;
using Domain.Services;
using System;
using UserInterface.Misc;

namespace UserInterface
{
    public partial class RetrievePassword : BoardPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string pageTitle = (string)GetLocalResourceObject("Title");
            MasterPage.TitleGenerator.PageTitle = pageTitle;
            MasterPage.HeaderText = pageTitle;
            MasterPage.AddPathItem(pageTitle, "RetrievePassword.aspx");
        }

        protected void SubmitButton_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                string username = UsernameTextBox.Text.Trim();
                string email = EmailTextBox.Text.Trim();

                User user = UserService.GetByUsernameAndEmail(username, email);

                if (user != null)
                {
                    if (user.Status == UserStatus.Activated)
                    {
                        UserService.UpdateStatus(user, UserStatus.RetrievingPassword);

                        MailParser mailParser = new MailParser(Server.MapPath("~/Emails/PasswordRetrieval.xml"));
                        mailParser.AddBodyTag("Username", user.Username);
                        mailParser.AddBodyTag("ActivationUrl", "http://" + Request.ServerVariables["HTTP_HOST"] + "/ActivateAccount.aspx?userId=" + user.Id + "&activationKey=" + user.ActivationKey);

                        MailSender mailSender = new MailSender(mailParser);
                        mailSender.AddRecipient(user.Email);
                        mailSender.Send();

                        DieMessage(DieMessageType.Information, "PasswordRetrievalEmailSent");
                    }
                    else
                    {
                        MasterPage.Messages.AddCritical((string)GetLocalResourceObject("UserNotActivated"));
                    }
                }
                else
                {
                    MasterPage.Messages.AddCritical((string)GetLocalResourceObject("UserNotFound"));
                }
            }
            else
            {
                MasterPage.Messages.AddCritical(Resources.Resource.InvalidFormData);
            }
        }
    }
}